<template>
  <div class="ies-form"
       :style="{width:$attrs.width?$attrs.width:'auto'}">
    <div class="ies-form-content">
      <el-form :label-width="$attrs['label-width']?$attrs['label-width']:'auto'"
               :inline="true"
               :rules="rulesList"
               :model="ruleForm"
               ref="ruleForm"
               :class="$attrs['clo-width']?'flex justify-between flex-wrap demo-form-inline':'demo-form-inline'">
        <template slot-scope
                  v-for="(item, index) in formList ">
          <el-form-item v-if="item.type!=='length-width-height'&&!item.type.includes('selectInput')&&(item.isShow!==undefined?item.isShow:true)"
                        :key="index"
                        :label="item.type==='inputIconBtn'?'':labelName(item.label)"
                        :prop="item.type==='inputIconBtn'?null:(item.prop?item.prop:rulesList[item.name]!==undefined?item.name:null)"
                        :style="{width:item.itemWidth?item.itemWidth:($attrs['clo-width']?$attrs['clo-width']:'auto')}">
            <el-input v-if="item.type === 'input'"
                      v-model="ruleForm[item.name]"
                      clearable
                      :precision="item.precision!==undefined?item.precision:null"
                      :step="item.step!==undefined?item.step:null"
                      :type="item.inputType?item.inputType:'text'"
                      :disabled="item.disabled?item.disabled:false"
                      :readonly="operationType==='readonly'?true:(item.readonly!==undefined?item.readonly:false)"
                      :placeholder="item.placeholder?placeholder('input',item.placeholder):null"
                      :style="{width:item.unitText!==undefined?(item.width||inputWidth?`calc(${item.width||inputWidth} - 30px)`:`calc(100% - 30px)`):(item.width?item.width:inputWidth)}"
                      :min="item.min?item.min:defaultNumber"
                      :max="item.max?item.max:null"
                      :autocomplete="item.autocomplete===undefined?'new-password':item.autocomplete"
                      @change="item.change&&(Object.prototype.toString.call(item.change)==='[object Function]')?item.change($event,item):null"
                      @focus="item.focus&&(Object.prototype.toString.call(item.focus)==='[object Function]')?item.focus($event,item):null"
                      @blur="item.blur&&(Object.prototype.toString.call(item.blur)==='[object Function]')?item.blur($event,item):null"></el-input>
            <span class="margin-left-sm"
                  v-if="item.type === 'input'&&item.unitText!==undefined">{{item.unitText}}</span>

            <el-input v-if="item.type === 'textarea'"
                      :autosize="{ minRows: item.options&&item.options.minRows?item.options.minRows:1, maxRows: item.options&&item.options.maxRows?item.options.maxRows:4}"
                      v-model="ruleForm[item.name]"
                      clearable
                      :disabled="item.disabled?item.disabled:false"
                      :readonly="operationType==='readonly'?true:(item.readonly!==undefined?item.readonly:false)"
                      type="textarea"
                      :maxlength="item.options&&item.options.maxlength?item.options.maxlength:null"
                      show-word-limit
                      :style="{width:item.width?item.width:inputWidth}"
                      :placeholder="item.placeholder?placeholder('input',item.placeholder):null"></el-input>
            <el-select v-if="item.type === 'select'"
                       v-model="ruleForm[item.name]"
                       :multiple="item.multiple!==undefined&&item.multiple?true:false"
                       :disabled="operationType==='readonly'?true:(item.disabled!==undefined?item.disabled:false)"
                       :placeholder="item.placeholder?placeholder('select',item.placeholder):null"
                       :style="{width:item.width?item.width:inputWidth}"
                       v-loading="item.loading!==undefined&&item.loading?true:false"
                       :allow-create="item.allowCreate!==undefined?true:false"
                       :filterable="item.allowCreate!==undefined?true:false"
                       :autocomplete="item.autocomplete===undefined?'new-password':item.autocomplete"
                       default-first-option
                       :data-aloo="item.allowCreate"
                       clearable
                       @focus="item.focus&&(Object.prototype.toString.call(item.focus)==='[object Function]')?item.focus($event,item):null"
                       @change="item.change&&(Object.prototype.toString.call(item.change)==='[object Function]')?item.change($event,item):null">
              <el-option v-for="(item1,index1) in item.selectOptions"
                         :key="index1"
                         :label="labelName(item1.label)"
                         :value="item1.value"
                         :disabled="item1.disabled===undefined?false:item1.disabled"></el-option>
            </el-select>
            <el-radio-group v-if="item.type === 'radio'"
                            v-model="ruleForm[item.name]"
                            :disabled="operationType==='readonly'?true:(item.disabled!==undefined?item.disabled:false)"
                            :style="{width:item.width?item.width:inputWidth}"
                            @change="item.change&&(Object.prototype.toString.call(item.change)==='[object Function]')?item.change($event,item):null">
              <el-radio v-for="(item1,index1) in item.selectOptions"
                        :key="index1"
                        :label="item1.value">{{labelName(item1.label)}}</el-radio>
            </el-radio-group>
            <el-checkbox-group v-if="item.type === 'checkbox'"
                               v-model="ruleForm[item.name]"
                               :disabled="operationType==='readonly'?true:(item.disabled!==undefined?item.disabled:false)"
                               :style="{width:item.width?item.width:inputWidth,marginLeft:item.typeVal==='single'?item.labelWidth:''}">
              <el-checkbox v-for="(item1,index1) in item.selectOptions"
                           :key="index1"
                           :label="item1.value">{{labelName(item1.label)}}</el-checkbox>
            </el-checkbox-group>
            <el-date-picker v-if="item.type === 'daterange'"
                            v-model="ruleForm[item.name]"
                            type="daterange"
                            range-separator="-"
                            :start-placeholder="$t('el.datepicker.startDate')"
                            :end-placeholder="$t('el.datepicker.endDate')"
                            :readonly="operationType==='readonly'?true:(item.readonly!==undefined?item.readonly:false)"
                            :style="{width:item.width?item.width:inputWidth}"
                            :disabled="item.disabled?item.disabled:false"
                            :picker-options="item.pickerOptions!==undefined?item.pickerOptions:null"
                            :format="item.format!==undefined?item.format:null"
                            :value-format="item.valueFormat!==undefined?item.valueFormat:null"
                            :default-time="item.defaultTime!==undefined?item.defaultTime:null" />
            <el-date-picker v-if="item.type === 'date'"
                            v-model="ruleForm[item.name]"
                            type="date"
                            :readonly="operationType==='readonly'?true:(item.readonly!==undefined?item.readonly:false)"
                            :style="{width:item.width?item.width:inputWidth}"
                            :disabled="item.disabled?item.disabled:false"
                            :picker-options="item.pickerOptions!==undefined?item.pickerOptions:null"
                            :placeholder="$t('el.datepicker.selectDate')"
                            :format="item.format!==undefined?item.format:null"
                            :value-format="item.valueFormat!==undefined?item.valueFormat:null"
                            :default-time="item.defaultTime!==undefined?item.defaultTime:null"></el-date-picker>
            <el-date-picker v-if="item.type === 'datetime'"
                            v-model="ruleForm[item.name]"
                            type="datetime"
                            :readonly="operationType==='readonly'?true:(item.readonly!==undefined?item.readonly:false)"
                            :style="{width:item.width?item.width:inputWidth}"
                            :placeholder="$t('el.datepicker.selectDate')"
                            :disabled="item.disabled?item.disabled:false"
                            :picker-options="item.pickerOptions!==undefined?item.pickerOptions:null"></el-date-picker>
            <el-date-picker v-if="item.type === 'datetimerange'"
                            v-model="ruleForm[item.name]"
                            type="datetimerange"
                            :readonly="operationType==='readonly'?true:(item.readonly!==undefined?item.readonly:false)"
                            :style="{width:item.width?item.width:inputWidth}"
                            :disabled="item.disabled?item.disabled:false"
                            :picker-options="item.pickerOptions!==undefined?item.pickerOptions:null"
                            :placeholder="$t('el.datepicker.selectDate')"></el-date-picker>
          </el-form-item>
        </template>
        <slot name="inSide" />
      </el-form>
      <slot name="outSide" />
    </div>
  </div>
</template>

<script>
import _ from 'lodash'
import Cookies from 'js-cookie'
export default {
  props: {
    formList: {
      type: Array,
      default: function () {
        return []
      }
    },
    inputWidth: {
      type: String,
      default: '217px'
    },
    operationType: {
      type: String,
      default: 'edit'// (可编辑：edit；只读： readonly)
    },
    defaultNumber: {
      type: Number,
      default: 0
    },
    rules: {
      type: Object,
      default: function () {
        return {}
      }
    },
    ruleForm: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data() {
    return {
      ruleFormData: {}

    }
  },
  computed: {
    rulesList() {
      return this.rules
    }
  },
  watch: {
    ruleForm(newVal, oldVal) {
      if (this.formList.length > 0) {
        this.formList.map((item) => {
          if (item.type.includes('selectInput')) {
            const keyNames = item.name.split('-')
            if (newVal[keyNames[0]] !== '' && newVal[keyNames[1]] !== '') {
              this.$set(newVal, item.name, newVal[keyNames[0]] + '-' + newVal[keyNames[1]])
            } else {
              this.$set(newVal, item.name, '')
            }
          }
          if (item.type === 'length-width-height') {
            const keyNames = item.name.split('-')
            if (newVal[keyNames[0]] !== '' && newVal[keyNames[1]] !== '' && newVal[keyNames[2]] !== '') {
              this.$set(newVal, item.name, newVal[keyNames[0]] + '-' + newVal[keyNames[1]] + '-' + newVal[keyNames[2]])
            } else {
              this.$set(newVal, item.name, '')
            }
          }
        })
      }
    }
  },
  created() {
  },
  mounted() {
    const lengWidthHeight = document.querySelectorAll('.length-width-height')
  },
  destroyed() { //
    this.resetForm()
  },
  methods: {
    getTimeLength(time, data) {
      let timeVal = time.getTime()
      if (data !== undefined) {
        const curDate = (new Date()).getTime()
        const seven = Number(data) * 24 * 3600 * 1000
        const sevenDays = curDate - seven
        timeVal = time.getTime() > Date.now() || time.getTime() < sevenDays
      }

      return timeVal
    },

    selectChange(val, item) { // input-select组合
      const name = item.name.split('-')
      this.$set(this.ruleForm, item.name, this.ruleForm[name[0]] + '-' + this.ruleForm[name[1]])
    },
    inputChange(val, item) { // input-select组合
      const name = item.name.split('-')
      this.$set(this.ruleForm, item.name, this.ruleForm[name[0]] + '-' + this.ruleForm[name[1]])
    },
    getName(data, index) {
      const val = data.split('-')[index]
      return val
    },
    getRuleFormChange() { // 获取实时输入值
      return this.ruleForm
    },
    changeOption(val, item) {
      this.formList.map((v) => {
        if (item.changeTo === v.name) {
          if (val) {
            v[item.changeOptions.opt] = !item.changeOptions.value
          } else {
            v[item.changeOptions.opt] = item.changeOptions.value
          }
        }
      })
    },
    placeholder(type, data) {
      if (data.indexOf('.') !== -1) {
        if (type === 'select') {
          return data ? (this.$t('el.select.placeholder') + ' ' + this.$t(`${data}`)) : this.$t('el.select.placeholder')
        }
        if (type === 'input') {
          return data ? (this.$t('input.placeholder') + ' ' + this.$t(`${data}`)) : this.$t('input.placeholder')
        }
        if (type === 'daterange' || type === 'date') {
          return data ? (this.$t('input.placeholder') + ' ' + this.$t(`${data}`)) : this.$t('input.placeholder')
        }
      } else if (data.indexOf('i18n') !== -1) {
        const str = this.$utils.getLabelName(data, this)
        if (Cookies.get('lang') === 'en') {
          if (type === 'select') {
            return this.$t('el.select.placeholder') + ' ' + str
          }
          if (type === 'input') {
            return this.$t('input.placeholder') + ' ' + str
          }
          if (type === 'select') {
            return this.$t('el.select.placeholder') + ' ' + str
          }
        } else {
          if (type === 'select') {
            return this.$t('el.select.placeholder') + str
          }
          if (type === 'input') {
            return this.$t('input.placeholder') + str
          }
          if (type === 'select') {
            return this.$t('el.select.placeholder') + str
          }
        }
      } else {
        return data
      }
    },
    labelName(data) { // 多语言切换
      if (data !== undefined) {
        if (data.indexOf('.') !== -1) {
          return this.$t(data)
        } else if (data.indexOf('i18n') !== -1) {
          return this.$utils.getLabelName(data, this)
        } else {
          return data
        }
      } else {
        return ''
      }
    },
    submit() {
      // const ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
      const ruleForm = this.ruleForm

      const dateTwins = []
      const datetimes = []
      this.formList.map(item => {
        if (item.type === 'daterange') {
          dateTwins.push(item)
        }
        if (item.type === 'datetimerange') {
          datetimes.push(item)
        }
        if (item.type === 'date' || item.type === 'datetime') {
          ruleForm[item.name] = ruleForm[item.name]
            ? this.$utils.formatDateTime(ruleForm[item.name])
            : ''
        }
        if (item.type === 'length-width-height') {
          const keyNames = item.name.split('-')
          ruleForm[keyNames[0]] = ruleForm[keyNames[0]]
          ruleForm[keyNames[1]] = ruleForm[keyNames[1]]
          ruleForm[keyNames[2]] = ruleForm[keyNames[2]]
          if (ruleForm[keyNames[0]] !== '' && ruleForm[keyNames[0]] !== '' && ruleForm[keyNames[0]] !== '') {
            ruleForm[item.name] = ruleForm[keyNames[0]] + '-' + ruleForm[keyNames[1]] + '-' + ruleForm[keyNames[2]]
          }
        }
        if (item.isShow !== undefined) { // 不显示的时候不提交参数
          const keyNames = item.name.split('-')
          if (!item.isShow) {
            if (item.type.includes('selectInput')) {
              delete ruleForm[keyNames[0]]
              delete ruleForm[keyNames[1]]
            } else if (item.type === 'length-width-height') {
              delete ruleForm[keyNames[0]]
              delete ruleForm[keyNames[1]]
              delete ruleForm[keyNames[2]]
            } else {
              delete ruleForm[item.name]
            }
          } else {
            if (item.type.includes('selectInput')) {
              ruleForm[item.name] = ruleForm[keyNames[0]] + '-' + ruleForm[keyNames[1]]
              this.ruleForm[item.name] = ruleForm[keyNames[0]] + '-' + ruleForm[keyNames[1]]
            } else if (item.type === 'length-width-height') {
              ruleForm[item.name] = ruleForm[keyNames[0]] + '-' + ruleForm[keyNames[1]] + '-' + ruleForm[keyNames[2]]
              this.ruleForm[item.name] = ruleForm[keyNames[0]] + '-' + ruleForm[keyNames[1]] + '-' + ruleForm[keyNames[2]]
            }
          }
        }
        if (item.inputType !== undefined && item.inputType === 'Number') { // 数字类型
          ruleForm[item.name] = Number(ruleForm[item.name])
        }
      })
      this.timeTransfor(dateTwins, ruleForm)
      this.timeTransfor(datetimes, ruleForm)
      let flag = false


      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const submitData = JSON.parse(JSON.stringify(ruleForm))
          Object.keys(submitData).forEach(key => {
            if (key.includes('-')) {
              delete submitData[key]
            }
          })
          // delete ruleForm['startTime-endTime']
          this.$emit('submit', submitData)
          this.ruleFormData = submitData
          flag = true
        } else {
          // eslint-disable-next-line prefer-promise-reject-errors
          flag = false
        }
      })

      if (flag) {
        return this.ruleFormData
      }
    },
    timeTransfor(data, ruleForm) { // 时间格式转换
      if (data.length > 0) { // 时间格式转换
        data.map(item => {
          Object.keys(item).forEach(key => {
            if (key === 'name') {
              const nameOptions = item[key].split('-')
              if (nameOptions.length > 0) {
                nameOptions.forEach((item2, index) => {
                  ruleForm[item2] = ''
                  if (ruleForm[item[key]] && ruleForm[item[key]][index]) {
                    ruleForm[item2] = this.$utils.formatDateTime(ruleForm[item[key]][index])
                  }
                })
              }
            }
          })
        })
      }
      return ruleForm
    },
    add() {
      this.$emit('add')
    },
    resetForm() {
      this.formList.map((item) => {
        item.value = ''
      })
      Object.keys(this.ruleForm).forEach(key => {
        this.ruleForm[key] = ''
      })
    }

  }

}

</script>

<style lang="scss" scoped>
@import '~@styles/variable.scss';
.ies-form {
  .demo-form-inline {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  &/deep/ .el-form {
    .el-form-item {
      margin-bottom: 18px;
      &.ies-select-input {
        align-items: flex-start;
        .el-form-item__content {
          .el-form-item {
            margin-bottom: 0;
            margin-right: 0;
          }
        }
      }
      &.length-width-height {
        position: relative;
        .error-icon {
          position: absolute;
          top: calc(50% - 6px);
          left: 0;
        }
        .el-form-item__content {
          .el-form-item {
            margin-bottom: 0;
            margin-right: 0;
          }
        }
      }
      .el-form-item__label {
        white-space: nowrap;
      }
    }
  }
}
</style>
